package com.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.Result;
import com.example.entity.User;
import com.example.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@Api(tags = {"用户接口列表"})
@RestController
@RequestMapping("/users")
@Slf4j
public class UsersController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PasswordEncoder passwordEncoder;


    @ApiOperation("通过个人信息界面修改用户")
    @PutMapping
    public Result<?> updateUser(HttpServletRequest request, @RequestBody User user) {
        log.info(user.toString());

        String header = request.getHeader("X-Token");
        Object o = redisTemplate.opsForValue().get(header);
        User user1 = (User) o;

        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getId, user1.getId());
        User one = userService.getOne(userLambdaQueryWrapper);

        if (user.getUsername() != null) {
            one.setUsername(user.getUsername());
        }
        if (user.getPassword() != null) {
            one.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        if (user.getPhone() != null) {
            one.setPhone(user.getPhone());
        }
        if (user.getEmail() != null) {
            one.setEmail(user.getEmail());
        }
        userService.updateById(one);
        return Result.success("修改用户成功");
    }
}
